<template>
  <div class="account">
    <div class="login-container">
      <div class="login-container-center">
        <div class="login-container__header">
          <span :class="{'bold': tabCheck}" @click="tabCheck = true">密码登录</span>
          <span :class="{'bold': !tabCheck}" @click="tabCheck = false">验证码登录</span>
        </div>
        <form class="zent-form zent-form--horizontal">
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
            <div class="account-input">
              <el-row :gutter="30">
                <el-col :span="8">
                  <el-select v-model="loginForm.telSource" class="account-select">
                    <el-option label="中国+86" value="0" />
                  </el-select>
                </el-col>
                <el-col :span="16">
                  <el-form-item prop="tel">
                    <el-input ref="username" v-model="loginForm.tel" placeholder="请输入账号" class="account-text" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div v-if="tabCheck" class="account-input">
              <el-row :gutter="30">
                <el-col :span="24">
                  <el-form-item prop="pwd">
                    <el-input ref="password" v-model="loginForm.pwd" placeholder="请输入密码" class="account-text" show-password />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div v-else class="retrieve-input">
              <el-row :gutter="30">
                <el-col :span="24">
                  <el-form-item prop="telCode" class="telCodeRow">
                    <el-input ref="telCode" v-model="loginForm.telCode" placeholder="请输入手机验证码" class="retrieve-text" />
                    <div class="telCodeBtn" :class="{'isDisabled': loginForm.tel.length !== 11 || !isCheck}" @click="sendCode()">{{ telCodeText }}</div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
          <div class="login-container__auto">
            <el-checkbox v-model="checkUserName">保存用户账号</el-checkbox>
            <button type="button" class="login-container__btn" @click="handleLogin" @keyup.enter="handleLogin">
              <span>登 录</span>
            </button>
            <div class="login-container__links">
              <div class="login-container__auto__check">
                <el-checkbox v-model="agreementCheck">我已阅读并同意</el-checkbox>
                <a>用户协议</a>、<a>隐私政策</a>
              </div>
              <div class="login-container__links__actions">
                <span class="js-retrieve-btn" @click="goPassWord">忘记密码</span>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
    <div class="footer">
      <label>©2019 上海Ibeeking信息科技有限公司 <a href="https://beian.miit.gov.cn/" target="black">沪ICP备2022028769号</a></label>
      <div style="display:inline-block">
        <a target="_blank" href=" " style="display:inline-block;text-decoration:none;display:flex;">
          <img src="../../assets/common/beian.png" style="width: 25px;">
          <p style="margin: 0px 0px 0px 5px; color:#fff;">
            <a href="http://www.beian.gov.cn" target="black" style="line-height: 26px;">沪公网安备
              31011202008554号
            </a>
          </p>
        </a>
      </div>
    </div>
  </div>
</template>

<script>
import { loginIn } from '@/api/login'
import { rsa } from '@/utils/rsa'
import { publicKey, sendCode } from '@/api/public'
import { setToken } from '@/utils/auth'
import { getLocalStorage, setLocalStorage, removeLocalStorage } from '@/utils/localStorage'
const STORAGE_SAVE_USER_NAME_KEY = 'savedUserNameKey'
export default {
  name: 'Login',
  data() {
    return {
      loginRules: {
        tel: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ]
      },
      loginForm: {
        telSource: '0',
        tel: '',
        pwd: ''
      },
      passwordType: 'password',
      tabCheck: true,
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      checkUserName: false,
      agreementCheck: true,
      telCodeText: '获取验证码',
      isCheck: true,
      sendCodeKey: ''
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    var t = this
    var key = ''
    document.onkeydown = function(e) {
      if (window.event === undefined) {
        key = e.keyCode
      } else {
        key = window.event.keyCode
      }
      // enter的ASCII码是13
      if (key === 13) {
        t.handleLogin()
      }
    }
  },
  mounted() {
    if (this.loginForm.tel === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.pwd === '') {
      this.$refs.password.focus()
    }
    if (window.localStorage) {
      const savedUserName = getLocalStorage(STORAGE_SAVE_USER_NAME_KEY)
      if (savedUserName !== null) {
        this.loginForm.tel = savedUserName
        this.checkUserName = true
      }
    }
  },
  methods: {
    goPassWord() {
      this.$router.push('/retrieve-pass')
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          if (!this.agreementCheck) {
            this.$message.error('请同意服务协议')
            return false
          }
          publicKey().then(res => {
            localStorage.setItem('rsa', res)
            const client_secret = rsa('123456')
            const password = rsa(this.loginForm.pwd)
            const paramsStr = this.tabCheck ? `?grant_type=password&username=${this.loginForm.tel}&password=${password}&client_id=mall-tenant&client_secret=${client_secret}` : `?grant_type=sms_code&phone=${this.loginForm.tel}&code=${this.loginForm.telCode}&key=${this.sendCodeKey}&client_id=mall-tenant&client_secret=${client_secret}`
            loginIn(paramsStr).then(response => {
              setToken(response.token_type + ' ' + response.access_token)
              if (response.am_demo_user) {
                setLocalStorage('AM_DEMO_USER', response.am_demo_user)
              } else {
                setLocalStorage('AM_DEMO_USER', false)
              }
              this.$router.push({ path: 'shop-list', query: this.$route.query })
              if (this.checkUserName) {
                setLocalStorage(STORAGE_SAVE_USER_NAME_KEY, this.loginForm.tel)
              } else {
                removeLocalStorage(STORAGE_SAVE_USER_NAME_KEY)
                this.checkUserName = false
              }
            })
          })
        } else {
          return false
        }
      })
    },
    sendCode() {
      if (this.isCheck && this.loginForm.tel.length === 11) {
        sendCode({
          tel: this.loginForm.tel
        }).then(response => {
          this.sendCodeKey = response
          let time = 60
          this.isCheck = false
          this.telCodeText = `重新获取 ${time}s`
          this.timer = setInterval(() => {
            time--
            this.telCodeText = `重新获取 ${time}s`
            if (time === 0) {
              this.isCheck = true
              this.telCodeText = '获取验证码'
              clearInterval(this.timer)
            }
          }, 1000)
        })
      }
    },
    openUserAgreementDialog() {
      this.$router.push('/user-agreement')
    },
    openPrivacyPolicyDialog() {
      this.$router.push('/privacy-policy')
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;
// 解决记住密码的背景颜色
input:-webkit-autofill {
    -webkit-text-fill-color: #fff !important;/*浏览器记住密码的字的颜色*/
    transition: background-color 5000s ease-in-out 0s;/*通过延时渲染背景色变相去除背景颜色*/
    caret-color: #acfff2;/*光标颜色*/
}

input:focus { outline: none; }/*外边框线去除*/
.account{
  position: relative;
  width: 100vw;
  height: 100vh;
  min-width: 1200px;
  min-height: 680px;
  overflow: auto;
  background: #f2f3f5;
  background: url("~@/assets/login/bg.jpg") no-repeat center center;
  background-size: 100% 100%;
  /* reset element-ui css */
  .login-container {
    width: 550px;
    border-radius: 6px;
    // background: #fff;
    overflow: hidden;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-pack: justify;
    justify-content: space-between;
    position: relative;
    // width: 948px;
    top: 46%;
    left: 51%;
    padding: 50px 56px 60px;
    transform: translate(-50%,-50%);
    box-sizing: border-box;
    .login-container-center {
      .login-container__header{
        cursor: pointer;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-align: baseline;
        align-items: baseline;
        padding-bottom: 30px;
        font-size: 20px;
        color: #fff;
        span:first-child {
          margin-right: 24px;
        }
        .bold {
          font-weight: 500;
          font-size: 26px;
          color: #fff;
          cursor: default;
        }
      }
      .zent-form {
        margin-bottom: 30px;
        width: auto;
        .retrieve-input {
          padding-top: 30px;
          .telCodeRow {
            position: relative;
            .isDisabled {
              color: #969799 !important;
              cursor: not-allowed !important;
            }
            .telCodeBtn {
              position: absolute;
              right: 0;
              top: 50%;
              transform: translateY(-50%);
              font-size: 16px;
              color: #155bd4;
              cursor: pointer;
            }
          }
          .retrieve-text,.retrieve-select {
            .el-input__inner {
              border-width: 0;
              border-bottom-width: 1px;
              border-radius: 0;
            }
          }
          .el-form-item {
            margin-bottom: 0;
          }
        }
        .account-input {
          padding-top: 30px;
          .account-text,.account-select {
            .el-input__inner {
              border-width: 0;
              border-bottom-width: 1px;
              border-radius: 0;
            }
          }
          .el-form-item {
            margin-bottom: 0;
          }
        }
        .login-container__auto {
          color: #323232;
          margin-top: 45px;
          .el-checkbox__label{
            color: #fff;
          }
          .el-checkbox__inner{
            box-shadow: 0px 0px 1px #fff;
            background-color: transparent;
            border: 1.5px solid #69bff4;
          }
          .login-container__btn {
            margin: 16px 0;
            height: 48px;
            line-height: 46px;
            // background: #155bd4;
            background: url("~@/assets/login/btn.png") no-repeat center center;
            background-size: 100% 100%;
            font-size: 18px;
            color: #fff;
            display: block;
            width: 100%;
            padding: 0;
            border: 1px solid #bbb;
            text-align: center;
            vertical-align: middle;
            box-sizing: border-box;
            cursor: pointer;
            transition: all .3s;
            font-family: inherit;
            border-radius: 2px;
            border-color: transparent;
          }
          .login-container__btn:hover {
            background: url("~@/assets/login/btn.png") no-repeat center center;
            background-size: 100% 100%;
              // background: #3773da;
              // color: #fff;
          }
          .login-container__links {
            display: -ms-flexbox;
            display: flex;
            -ms-flex-pack: justify;
            justify-content: space-between;
            align-items: center;
            .login-container__auto__check {
              color: #0067d5;
              .el-checkbox__input.is-checked + .el-checkbox__label {
                color: #fff;
              }
              a {
                color: #0067d5;
                font-size: 14px;
                line-height: 19px;
              }
            }
            .login-container__links__actions {
              font-size: 14px;
              .js-retrieve-btn {
                color: #fff;
                cursor: pointer;
              }
            }
          }
        }
      }
    }
  }
   .el-input__inner {
      border-width: 0;
      border-bottom-width: 1px;
      border-radius: 0;
      background: transparent !important;
      border-bottom: 1px solid #1e94d4;
      color: #fff;
      &::placeholder {
        color: #fff;
      }
      &::-webkit-input-placeholder {
        /* Chrome/Opera/Safari */
        color: #fff;
      }
      &:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 适配火狐 */
        color: #fff;
        /* 设置opacity  解决firefox不生效问题 */
        opacity: 1;
      }
      &::-moz-placeholder {
        /* Mozilla Firefox 19+ 适配火狐 */
        color: #fff;
        opacity: 1;
      }
      &:-ms-input-placeholder {
        /* Internet Explorer 10+  适配ie*/
        color: #fff;
      }
  }
  .footer {
    letter-spacing: 0.2px;
    font-size: 16px;
    position: absolute;
    bottom: 50px;
    left: 0;
    right: 0;
    margin: 0 auto;
    color: #fff;
    z-index: 999;
    // font-size: 0.0875rem;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  @media screen and (max-width: 1600px){
    .login-container__header{
      padding-bottom: 20px !important;
    }
    .account-input{
      padding-top: 20px !important;
    }
    .login-container__auto{
      margin-top: 35px !important;
    }
  }
}
</style>
